'''
@File    :   project_request.py
@Time    :   2025/07/11 10:21:58
@Author  :   ZhangQifeng 
'''
import requests
import time
from urllib.parse import urlparse
from functools import wraps
from core.logger import get_logger
from typing import Optional, Dict, Any


log = get_logger(__name__)

def validate_url(url: str) -> None:
    """Basic URL validation"""
    if not url:
        raise ValueError("URL cannot be empty")
    try:
        result = urlparse(url)
        if not all([result.scheme, result.netloc]):
            raise ValueError("Invalid URL format")
    except Exception as e:
        raise ValueError(f"URL validation failed: {e}")

def log_request_info(func=None, *, enable_logging: bool = True):
    """可配置的请求日志装饰器"""
    if func is None:
        return lambda f: log_request_info(f, enable_logging=enable_logging)
        
    @wraps(func)
    def wrapper(*args, **kwargs):
        if not wrapper._enable_logging:
            return func(*args, **kwargs)
            
        SENSITIVE_FIELDS = {'cookies', 'headers', 'authorization'}
        log.debug("准备发起请求，参数如下：")
        for k, v in kwargs.items():
            log.debug(f"{k}: {'<隐藏>' if k.lower() in SENSITIVE_FIELDS else v}")
        
        start_time = time.time()
        result = func(*args, **kwargs)
        elapsed = time.time() - start_time

        try:
            resp_text = result.text[:200] + "..." if len(result.text) > 200 else result.text
            log.debug(
                f"请求完成 - 耗时: {elapsed:.2f}s, "
                f"状态码: {result.status_code}, "
                f"响应内容（前200字符）:\n{resp_text}"
            )
        except Exception as e:
            log.error(f"响应处理出错: {e}")

        return result
        
    wrapper._enable_logging = enable_logging
    wrapper.enable_logging = lambda: setattr(wrapper, '_enable_logging', True)
    wrapper.disable_logging = lambda: setattr(wrapper, '_enable_logging', False)
    return wrapper

@log_request_info
def post_with_json(
    url: str,
    payload: Optional[Dict] = None,
    headers: Optional[Dict] = None,
    cookies: Optional[Dict] = None,
    verify: bool = True,
    timeout: Optional[int] = None
) -> requests.Response:
    """发送 JSON POST 请求"""
    validate_url(url)
    
    try:
        return requests.post(
            url,
            json=payload or {},
            headers=headers or {},
            cookies=cookies or {},
            verify=verify,
            timeout=timeout
        )
    except requests.exceptions.RequestException as e:
        log.error(f"POST请求失败: {str(e)}")
        raise
    except Exception as e:
        log.error(f"未知错误: {str(e)}")
        raise

@log_request_info
def get(
    url: str,
    params: Optional[Dict] = None,
    headers: Optional[Dict] = None,
    cookies: Optional[Dict] = None,
    verify: bool = True,
    timeout: Optional[int] = None,
    stream: bool = False
) -> requests.Response:
    """发送 GET 请求"""
    validate_url(url)
    
    try:
        return requests.get(
            url=url,
            params=params or {},
            headers=headers or {},
            cookies=cookies or {},
            verify=verify,
            timeout=timeout,
            stream=stream
        )
    except requests.exceptions.RequestException as e:
        log.error(f"GET请求失败: {str(e)}")
        raise
    except Exception as e:
        log.error(f"未知错误: {str(e)}")
        raise

if __name__ == "__main__":    
    # 使用示例
    @log_request_info(enable_logging=False)  # 默认关闭日志
    def post_sensitive_data(url: str, payload: dict):
        pass

    @log_request_info  # 默认开启日志
    def get_public_data(url: str):
        pass

    # 运行时动态控制
    get_public_data.disable_logging()  # 临时关闭该函数的日志